<?php

namespace pengpai\modules\pepsi\controllers;

use DI\Annotation\Inject;
use GuzzleHttp\ClientInterface;
use yii\di\AnnotationSupport;
use yii\web\Controller;
use yii\wechat\OfficialAccountServiceInterface;

class WechatController extends Controller implements AnnotationSupport
{
    public $enableCsrfValidation = false;


    /**
     * @Inject
     * @var OfficialAccountServiceInterface
     */
    protected $WechatMpService;


    private $postObj;//获取数据

    /**
     * @Inject
     * @var ClientInterface
     */
    protected $httpClient;

    public function actionIndex()
    {
        $request = \Yii::$app->request;
        $echoStr = $request->get('echostr');
        $signature = $request->get('signature');
        $timestamp = $request->get('timestamp');
        $nonce = $request->get('nonce');

        if (!isset($echoStr)) {
            //返回信息
            $this->responseMsg();
        } else {
            if ($this->checkSignature($signature, $timestamp, $nonce)) {
                echo $echoStr;
            }
        }
    }

    //参数校验
    private function checkSignature($signature, $timestamp, $nonce)
    {
        $token = $_ENV["SNS_WECHAT_MP_TOKEN"];
        if (!$token) {
            echo 'TOKEN is not defined!';
        } else {
            $tmpArr = array($token, $timestamp, $nonce);
            // use SORT_STRING rule
            sort($tmpArr, SORT_STRING);
            $tmpStr = implode($tmpArr);
            $tmpStr = sha1($tmpStr);
            if ($tmpStr == $signature) {
                return true;
            } else {
                return false;
            }
        }
    }

    private function responseMsg()
    {
        $postStr = file_get_contents("php://input");
        if (!empty($postStr)) {
            $this->postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
            $rxType = trim($this->postObj->MsgType);

            switch ($rxType)
            {
                case "text":
                    $resultStr = $this->receiveText();
                    break;
                case "image":
                    $resultStr = $this->receiveImage();
                    break;
                case "location":
                    $resultStr = $this->receiveLocation();
                    break;
                case "voice":
                    $resultStr = $this->receiveVoice();
                    break;
                case "video":
                    $resultStr = $this->receiveVideo();
                    break;
                case "link":
                    $resultStr = $this->receiveLink();
                    break;
                case "event":
                    $resultStr = $this->receiveEvent();
                    break;
                default:
                    $resultStr = "unknow msg type: ".$rxType;
                    break;
            }
            echo $resultStr;
        } else {
            echo "";
            exit;
        }

    }

    private function receiveText()
    {
        $content = "text";
        return $this->transmitText($content);
    }

    private function receiveImage()
    {

        $content = "image";
        return $this->transmitText($content);
    }

    private function receiveLocation()
    {
        $content = "location";
        return $this->transmitText($content);
    }

    private function receiveVoice()
    {
        $content = "location";
        return $this->transmitText($content);
    }

    private function receiveVideo()
    {
        $content = "voice";
        return $this->transmitText($content);
    }

    private function receiveLink()
    {
        $content = "Link";
        return $this->transmitText($content);
    }

    private function receiveEvent()
    {
        $msgEvent = $this->postObj->Event;
        if ($msgEvent == "CLICK") {//点击菜单
            $eventKey = $this->postObj->EventKey;
            switch ($eventKey) {
                case "NEW_PLAN":
                    $content = "新人养成激励计划，敬请期待~";
                    break;
                default:
                    $content = "click event";
            }
        } elseif ($msgEvent == "subscribe") {
            //收到用户订阅关注消息
            //客服消息
            $customUrl = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=";
            $accessToken = $this->WechatMpService->getAccessToken()->getAccessToken();
            if (!$accessToken) {
                return "success";
            }

            $sendUrl = $customUrl . $accessToken;
            //客服回复文字
            $content = "欢迎加入【百事微促达】，这是一个为你量身定制福利平台，你的每一份付出，在这里都有回报！马上点击平台使用手册，快速掌握平台的使用方法吧！点击一页精要，速速开启你的微促达之旅，赚的你的第一桶金吧！还有更多玩法更多隐藏福利等你来发掘 ! 

点击链接，熟悉平台相关规则，火速开启你的微促达之旅吧！
平台操作指引：链接--促销员角色，同菜单栏配置的
积分获取手册：请见下方图片";

            $resultSend = $this->httpClient->request("POST",$sendUrl, [
                'headers' => ['Content-Type' => 'application/json'],
                "body" => json_encode([
                    "touser" => strval($this->postObj->FromUserName),
                    "msgtype" => "text",
                    "text" => [
                        "content" => $content
                    ],
                ], JSON_UNESCAPED_UNICODE)
            ])->getBody()->getContents();

            //客服回复图片
            //wAqrPlj6XB3MokLMOIjfA3HkR4rYA0QjwcJ2KYg2QlCJ63maMwkK5Dpy5fvYE5HQ
            $resultSend = $this->httpClient->request("POST",$sendUrl, [
                'headers' => ['Content-Type' => 'application/json'],
                "json" => [
                    "touser" => strval($this->postObj->FromUserName),
                    "msgtype" => "image",
                    "image" => [
                        "media_id" => "wAqrPlj6XB3MokLMOIjfA3HkR4rYA0QjwcJ2KYg2QlCJ63maMwkK5Dpy5fvYE5HQ"
                    ],
                ]
            ])->getBody()->getContents();

            return "success";
        } else {
            //$content = "event";
            return "";//返回空字符
        }
        return $this->transmitText($content);
    }

    private function transmitText($content)
    {
        $textTpl = "<xml>
            <ToUserName><![CDATA[%s]]></ToUserName>
            <FromUserName><![CDATA[%s]]></FromUserName>
            <CreateTime>%s</CreateTime>
            <MsgType><![CDATA[%s]]></MsgType>
            <Content><![CDATA[%s]]></Content>
            <FuncFlag>0</FuncFlag>
            </xml>";
        return sprintf($textTpl, $this->postObj->FromUserName, $this->postObj->ToUserName, time(), 'text', $content);
    }

}